<template>
  <div class="login">
    <el-form
      ref="loginRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">山河心理测评后台管理系统</h3>

      <!-- 账号 -->
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="账号"
          clearable
        >
          <template #prefix
            ><svg-icon icon-class="user" class="el-input__icon input-icon"
          /></template>
        </el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="密码"
          clearable
          show-password
        >
          <template #prefix
            ><svg-icon icon-class="password" class="el-input__icon input-icon"
          /></template>
        </el-input>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          placeholder="验证码"
          style="width: 65%"
          @keyup.enter="handleLogin"
        >
          <template #prefix
            ><svg-icon icon-class="validCode" class="el-input__icon input-icon"
          /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>

      <!-- 记住密码项 -->
      <el-checkbox
        v-model="loginForm.rememberMe"
        style="margin: 0px 0px 25px 10px"
        >记住密码</el-checkbox
      >

      <div style="float: right" v-if="register">
        <router-link class="link-type" :to="'/register'">立即注册</router-link>
      </div>

      <!-- 按钮 -->
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width: 100%"
          @click.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中 ， 请 稍 等...</span>
        </el-button>
      </el-form-item>
    </el-form>

    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2024 吉首大学山河心理测评工作室</span>
    </div>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

/* 绑定表单数据模型，同步字段值 */
const loginForm = ref({
  username: "admin",
  password: "admin123",
  rememberMe: false,
  code: "",
  uuid: "", // 唯一表示验证码请求，验证时客户端输入的验证码和uuid返回服务器验证
});

/* 绑定表单验证规则 */
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "账号不能为空" }],
  password: [{ required: true, trigger: "blur", message: "密码不能为空" }],
  code: [{ required: true, trigger: "change", message: "请输入右侧验证码" }],
};

//验证码url
const codeUrl = ref("");
//加载
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);
// 登录限制开关
const loginAttempts = ref(0); //连续点击登录失败次数
const isLocked = ref(false); //锁定
const lockEndTime = ref(null); //锁定时间

/* 侦听器的路由处理：登录后重定向 */
watch(
  route,
  /* 检查新路由，有新的则返回 */
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  //初始化时执行一次
  { immediate: true }
);

/* 点击登录按钮时被调用 */
function handleLogin() {
  /* 3次后触发登录锁定 */
  if (isLocked.value) {
    proxy.$message.error("请稍后重试或联系管理员");
    return;
  }

  /* 验证表单，检查是否符合定义的验证规则loginRules */
  proxy.$refs.loginRef.validate((valid) => {
    /* 表单验证通过 */
    if (valid) {
      loading.value = true;

      // 记住密码项
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), {
          expires: 30,
        });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }

      // 调用action的登录方法
      userStore
        .login(loginForm.value)
        .then(() => {
          loginAttempts.value = 0; // 重置失败次数
          const query = route.query; //当前 URL 的所有查询参数，通常是键值对
          /* 移除redirect参数 */
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          /* redirect.value指登录前用户访问的页面，false返回后面的 */
          router.push({ path: redirect.value || "/", query: otherQueryParams });
          proxy.$message.success("登录成功");
        })
        .catch(() => {
          loading.value = false; //取消加载
          loginAttempts.value += 1; // 增加失败次数
          /* 失败过多 */
          if (loginAttempts.value >= 3) {
            const currentTime = new Date().getTime();
            lockEndTime.value = currentTime +  5 * 1000; // 现有时间的基础上锁定
            localStorage.setItem("lockEndTime", lockEndTime.value); //存储结束时间
            isLocked.value = true;
            proxy.$message.error("账号已锁定，请5秒后重试");
            checkLockStatus();
          }
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode();
          }
        });
    }
  });
}

/* 获取验证码图像 */
function getCode() {
  getCodeImg().then((res) => {
    /* 默认启用验证码 */
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled;

    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

/* 当上面选择了记住密码，这里就会将信息存储到初始值，下一次登录便会填到对应框中 */
function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password:
      password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
  };
}

/* 检查登录锁定状态 */
function checkLockStatus() {
  const storedLockEndTime = localStorage.getItem("lockEndTime");
  if (storedLockEndTime) {
    const currentTime = new Date().getTime();
    /* 现<存，继续锁 */
    if (currentTime < storedLockEndTime) {
      isLocked.value = true;
      lockEndTime.value = storedLockEndTime;
      const remainingTime = storedLockEndTime - currentTime;
      setTimeout(() => {
        isLocked.value = false;
        loginAttempts.value = 0; // 重置失败次数
        localStorage.removeItem("lockEndTime");
        location.reload(); // 刷新页面
      }, remainingTime);
    } else {
      localStorage.removeItem("lockEndTime");
    }
  }
}

getCode();
getCookie();
checkLockStatus();
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/img.png");
  background-size: cover;
  background-position: center;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 20px;
  border: 5px solid  rgba(1,1,1,0.1);
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 40px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 30%;
  height: 40px;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  width: auto;
  height: 40px;
  padding-left: 12%;
}
</style>